package com.netty.simple;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.StandardCharsets;

/**
 * @Author 咕唧
 * @Date 2022/7/7 21:13
 * @Version 1.0
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("NettyClientHandler的channelActive方法执行了");
        //只能通过Unpooled的方式发送数据
        ctx.writeAndFlush(Unpooled.copiedBuffer("这是客户端发送第一条的消息".getBytes(StandardCharsets.UTF_8)));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("NettyClientHandler的channelRead方法执行了");
       // String content = ((ByteBuf) msg).toString(StandardCharsets.UTF_8);
       // System.err.println("收到了来自于服务端的消息:" + content);
        System.out.println(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
        System.out.println("NettyClientHandler的channelReadComplete方法执行了");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
